var https = require("https")
var express = require('express');
var router = express.Router();
var db = require("../util/DataBase.js")

var rankScore = require("../system/article_rank_score.js");

var articleService = require("../service/article.js");

router.post('/article/:id', function(req, res, next) {

  var values = [
    req.session.user.id,
    req.params.id
  ];

  db.query("INSERT INTO `article_fav` (`user_id`, `article_id`) VALUES (?, ?)", values, function (err, results) {

    if(err) {
      res.json(null, -1, "添加收藏失败");
    } else {
      articleService.adjustRank(req.params.id, rankScore.USER_FAV);
      res.json();
    }

  });

});

router.post('/article/:id/cancel', function(req, res, next) {

  var values = [
    req.params.id,
    req.session.user.id
  ];

  db.query("DELETE FROM `article_fav` WHERE `article_id` =? AND `user_id` = ?", values, function (err, results) {

    if(err) {
      res.json(null, -1, "取消收藏失败");
    } else {
      articleService.adjustRank(req.params.id, rankScore.USER_FAV * -1);
      res.json();
    }

  });

});

router.get('/article/:id', function(req, res, next) {

  var values = [
    req.params.id * 1,
    req.session.user.id * 1
  ];

  db.query("SELECT `id` FROM `article_fav` WHERE `article_id` = ? AND `user_id` = ?", values, function (err, results) {

    if(err) {
      res.json(null, -1, "获取收藏状态失败");
    } else {
      if(results.length > 0) {
        res.json(true);
      } else {
        res.json(false);
      }
    }

  });

});

router.get('/list', function(req, res, next) {

  var values = [
    req.session.user.id,
    req.query.startId * 1,
    req.query.len * 1
  ];

  db.query("SELECT article.id as id, article_fav.id as favId, article.title as title, article.content as content, article.question as question, article.user_id as user_id, article.create_datetime as create_datetime" +
    " FROM `article`, `article_fav`" +
    " WHERE article_fav.user_id = ? AND article_fav.article_id = article.id AND article_fav.id " + ( req.query.dir === "down" ? "<" : ">") + " ? ORDER BY article_fav.id DESC LIMIT ?",
    values, function(err, results) {

      if(err)
      {
        res.json(null, -1, "查询帖子失败");
        return;
      }

      if(results.length <= 0) {
        res.json([]);
        return;
      }

      var userLoaded = 0;

      for(var i = 0, l = results.length; i < l; ++ i) {
        var article = results[i];
        (function (_article) {
          _article.create_datetime_st = _article.create_datetime.getTime();
          db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", [_article.user_id], function (err, userResults) {
            _article.user = userResults[0];
            if(++ userLoaded == l) {
              res.json(results);
            }
          });
        })(article);
      }

  });

});

module.exports = router;
